package fr.nts.application.novadmin.front.security.provider;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import fr.nts.application.novadmin.database.model.employe.NovadminEmployeSimple;
import fr.nts.application.novadmin.front.security.model.NovadminUserDetails;
import fr.nts.application.novadmin.service.NovadminUserService;
import fr.nts.framework.front.security.provider.BasicSecurityProvider;
import fr.nts.framework.front.security.service.model.SimpleUserDetails;

/**
 * Le provider pour l'authentification d'une application web avec Spring Security pour l'application novadmin
 * 
 * @author sco
 * @version 1.0.0
 */
@Component("novadminAuthentificationProvider")
public class NovadminSecurityProvider extends BasicSecurityProvider{

    protected static final Logger log = LoggerFactory.getLogger(NovadminSecurityProvider.class);
   
    @Resource
    private NovadminUserService novadminUserService;
    
    /*
     * (non-Javadoc)
     * @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException{
        
    	log.debug("On cherche à s'authentifier sur l'application novadmin: {}", authentication);
    	
        return super.authenticate(authentication);
    }
    
    
    /**
     * Charge l'utilisateur Novadmin
     */
    protected UserDetails loadUserByUsername(final String username){
    	// L'utilisateur novadmin authentifié
    	NovadminUserDetails userDetails = new NovadminUserDetails((SimpleUserDetails)super.loadUserByUsername(username));
    	
    	// Les infos de l'utilisateur spécifique à Novadmin (peut être nul)
    	NovadminEmployeSimple employe = novadminUserService.loadNovadminEmployee(username);
    	
    	userDetails.setEmploye(employe);
    	
    	return userDetails;
    }
}